package com.example.blank700.note;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class NoteEditor extends AppCompatActivity {
    private static final String TAG = "Diary";
    public static final String EDIT_DIARY_ACTION = "andy.ham.DiaryEditor.EDIT_DIARY";
    public static final String INSERT_DIARY_ACTION = "andy.ham.DiaryEditor.action.INSERT_DIARY";
    public static final int MENU_ITEM_DELETE = Menu.FIRST + 1;

    // GreenDAO使用的变量
    private SQLiteDatabase db;
    private DaoMaster daoMaster;
    private DaoSession daoSession;
    private Note note;
    private NoteDao noteDao;

    private static final int STATE_EDIT = 0;
    private static final int STATE_INSERT = 1;
    private int mState;
    private EditText mTitleText;
    private EditText mBodyText;
    private int tagTypeNum = 0;
    private Button confirmButton;
    private long mid;

    private static final String[] tagName = {"全部", "生活", "工作"};
    private Spinner spinner;
    private ArrayAdapter adapter;
    private List list;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Intent intent = getIntent();
        final String action = intent.getAction();
        setContentView(R.layout.note_edit);

        mTitleText = (EditText) findViewById(R.id.title);
        mBodyText = (EditText) findViewById(R.id.body);
        confirmButton = (Button) findViewById(R.id.confirm);
        TextView tv_tag = (TextView) findViewById(R.id.tv_tag);
        Spinner spinner = (Spinner) findViewById(R.id.spinner);

        //初始化Dao
        InitDao();
        Log.d("action", action);

        //判断是新建还是编辑
        if (EDIT_DIARY_ACTION.equals(action)) {
            Bundle bundle = new Bundle();
            bundle = this.getIntent().getExtras();
            mid = bundle.getLong("id");//从NoteActivity获取到元祖的id
            note = noteDao.loadByRowId(mid);

            //读取出现有内容并设置
            mTitleText.setTextKeepState(note.getTitle());
            mBodyText.setTextKeepState(note.getBody());
            tagTypeNum = note.getTag();//现选类别
            Log.e("刚读取tagTypeNum的值的时候", "tagTypeNum value is " + tagTypeNum);

            setTitle("编辑便签");
        } else if (INSERT_DIARY_ACTION.equals(action)) {
            mState = STATE_INSERT;
            setTitle("新建便签");
        } else {
            Log.e(TAG, "no such action error");
            finish();
            return;
        }

        //确认按钮的监听器
        confirmButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mState == STATE_INSERT) {
                    insertNote();
                } else {
                    updateNote();
                }
                Intent intent1 = new Intent(NoteEditor.this, NoteActivity.class);
                startActivity(intent1);
                NoteEditor.this.finish();
            }
        });


        //构造ArrayList
        list = new ArrayList();
        for (int i = 0; i < tagName.length; ++i) {
            list.add(tagName[i]);
        }
        adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, list);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
        //配置Spinner
        spinner.setAdapter(adapter);
        //设置Spinner默认选中值
        spinner.setSelection(tagTypeNum);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //Toast.makeText(NoteEditor.this, "选择了:" + tagName[position], Toast.LENGTH_SHORT).show();
                parent.setVisibility(View.VISIBLE);
                tagTypeNum = position;
                Log.e("配置Spinner的时候", "tagTypeNum value is " + tagTypeNum);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

    private void InitDao() {
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "notes-db",
                null);
        db = helper.getWritableDatabase();
        daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();
        noteDao = daoSession.getNoteDao();
    }

    private void insertNote() {
        String title = mTitleText.getText().toString();
        String body = mBodyText.getText().toString();
        final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
                DateFormat.MEDIUM);
        String date = dateFormat.format(new Date());
        //插入
        Note note = new Note(null, title, body, date, tagTypeNum);
        noteDao.insert(note);
        Log.d("Note", "Inserted new note,ID:" + note.getId());
        Log.e("insert的时候", "tagTypeNum value is " + tagTypeNum);
    }

    private void updateNote() {
        String title = mTitleText.getText().toString();
        String body = mBodyText.getText().toString();
        final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
                DateFormat.MEDIUM);
        String date = dateFormat.format(new Date());

        Note note = noteDao.load(mid);
        note.setTitle(title);
        note.setBody(body);
        note.setDate(date);
        note.setTag(tagTypeNum);
        Log.e("update的时候", "tagTypeNum value is " + tagTypeNum);

        noteDao.save(note);
    }

    //添加右上角菜单键选项：删除
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(Menu.NONE, MENU_ITEM_DELETE, 0, R.string.menu_delete);
        return true;
    }

    //右上角菜单响应函数
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case MENU_ITEM_DELETE:
                noteDao.deleteByKey(mid);

                Toast.makeText(NoteEditor.this, R.string.diary_delete_success,
                        Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(NoteEditor.this, NoteActivity.class);
                startActivity(intent);
                NoteEditor.this.finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    //返回事件监听函数
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (mState == STATE_INSERT) {
            insertNote();
        } else {
            updateNote();
        }
        Intent intent1 = new Intent(NoteEditor.this, NoteActivity.class);
        startActivity(intent1);
        NoteEditor.this.finish();
        return super.onKeyDown(keyCode, event);
    }
}
